package com.k.ums.util;

import com.k.ums.context.Ums;
import com.k.ums.handler.RemoveCacheHandler;
import com.k.ums.model.RemoveCacheTask;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: kt
 * @CreateTime: 2022/2/18
 */
public class CacheUtils {
    private static RedisTemplate redisTemplate = Ums.getUmsContext().getBean(RedisTemplate.class);

    public static <V> void set(final String key, final V val) {
        redisTemplate.opsForValue().set(key, val);
    }

    public static <V> void set(final String key, final V val, final long timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, val, timeout, timeUnit);
    }

    public static <V> V get(final String key) {
        ValueOperations<String, V> valueOperations = redisTemplate.opsForValue();
        return valueOperations.get(key);
    }

    public static void delete(final String key) {
        redisTemplate.delete(key);
    }

    public static void deleteAsync(final String key, final long timeMillis) {
        long expireTime = System.currentTimeMillis() + timeMillis;
        RemoveCacheHandler.getInstance().execute(new RemoveCacheTask(key, expireTime));
    }

    public static void expire(final String key, final long timeout, final TimeUnit unit) {
        redisTemplate.expire(key, timeout, unit);
    }
    /*private static RedissonClient redissonClient;

    static {
        Config config = new Config();
        config.setCodec(StringCodec.INSTANCE);
        SingleServerConfig singleServer = config.useSingleServer();
        singleServer.setAddress("redis://192.168.43.133:6379");
        redissonClient = Redisson.create(config);
    }

    public static void set(String key, String value) {
        redissonClient.getBucket(key).set(value);
    }

    public static <V> void set(final String key, final V value, final Integer timeout, final TimeUnit timeUnit){
        redissonClient.getBucket(key).set(value,timeout,timeUnit);
    }

    public static void delete(String key) {
        redissonClient.getBucket(key).delete();
        System.out.println("Delete Cache Success");
    }

    public static void deleteAsync(String key, long timeMillis) {
        long expireTime = System.currentTimeMillis() + timeMillis;
        RemoveCacheHandler.getInstance().execute(new RemoveCacheTask(key, expireTime));
    }

    public static String get(String key){
        return redissonClient.<String>getBucket(key).get();
    }*/
}
